package ru.zombator.taskman.client.query.udp;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.DatagramChannel;
import java.rmi.RemoteException;

import ru.zombator.taskman.core.query.IPacket;
import ru.zombator.taskman.core.query.IResponderCli;
import ru.zombator.taskman.core.utils.PacketUtils;

/**
 * UDP-клиент
 * @author nvamelichev
 *
 */
public class UdpClient implements IResponderCli {
	private final static int UDP_SERVER_PORT = 5555;
	public final int PACKET_SIZE = 1024 * 20;
	
	private DatagramChannel ch;
	private SocketAddress addr;

	public UdpClient(String ipAddress) throws IOException {
		addr = new InetSocketAddress(ipAddress, UDP_SERVER_PORT);
		ch = DatagramChannel.open();
		ch.configureBlocking(true);
	}

	@Override
	public IPacket getResponse(IPacket request) throws RemoteException {
		ByteBuffer outBuf = PacketUtils.packetToBuffer(request, PACKET_SIZE);
		try {
			ch.send(outBuf, addr);

			ByteBuffer pktBuf = ByteBuffer.allocate(PACKET_SIZE);
			pktBuf.order(ByteOrder.LITTLE_ENDIAN);
			ch.receive(pktBuf);
			pktBuf.rewind();
			int payloadSize = pktBuf.getInt();
			
			return PacketUtils.bufferToPacket(pktBuf, payloadSize);
		} catch (IOException ioe) {
			throw new RemoteException(ioe.getMessage(), ioe);
		}
	}
}
